﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;
using DevExpress.Web.ASPxEditors;

namespace TireService.Web.UserControls
{
    public partial class ucCreateServiceCarCapacity : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void callbackCreateServiceCarCapacityPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int ContainerId)
        {
            // Show usercontrol edit form
            pCreateServiceCarCapacityPanel.Visible = true;

            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            // Load form data
            LoadUserControlData(db, ContainerId);
        }

        /// <summary>
        /// Function that load form data for tireset edit
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ContainerId">Container to get servicecars for</param>
        private void LoadUserControlData(TireServiceDB db, int ContainerId)
        {
            // Generate possible servicecars
            int[] servicecarids = db.GetContainerServiceCars(ContainerId);

            rbtnServiceCar.DataSource = db.ServiceCars.Where(d => servicecarids.Contains(d.ServiceCarId)).ToList();
            rbtnServiceCar.TextField = "ServiceCarId";
            rbtnServiceCar.ValueField = "ServiceCarId";
            rbtnServiceCar.DataBind();
        }

        /// <summary>
        /// Callback function that saves servicecar capacity
        /// </summary>
        protected void callBackSaveServiceCarCapacity_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values (0:servicecarid, 1:scheduledate, 2:starttime, 3:endtime, 4:slotinterval, 5:overlap)
                string[] param = e.Parameter.Split('|');

                TireServiceDB db = new TireServiceDB();

                int servicecarid = Convert.ToInt32(param[0]);
                DateTime datetime = Convert.ToDateTime(param[1]);

                if (!db.ScheduleDateExists(servicecarid, datetime))
                {
                    ServiceCarSchedule schedule = new ServiceCarSchedule();

                    schedule.ServiceCarId = servicecarid;
                    schedule.ScheduleDate = datetime;

                    db.AddServiceCarSchedule(schedule);

                    int startnumber = 1;
                    TimeSpan starttime = TimeSpan.Parse(param[2]);
                    TimeSpan latestendtime = TimeSpan.Parse(param[3]);

                    while (starttime.Add(TimeSpan.FromMinutes(Convert.ToInt32(param[4]))) < latestendtime)
                    {
                        ServiceCarScheduleDetail scheduledetail = new ServiceCarScheduleDetail();
                        schedule.ServiceCarScheduleDetails.Add(scheduledetail);
                        scheduledetail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.Available;
                        scheduledetail.SequenceNumber = startnumber;
                        scheduledetail.StartTime = starttime;
                        scheduledetail.EndTime = scheduledetail.StartTime.Add(TimeSpan.FromMinutes(Convert.ToInt32(param[4])));

                        // Calculate new starttime for next scheduledetail
                        starttime = scheduledetail.EndTime - TimeSpan.FromMinutes(Convert.ToInt32(param[5]));
                        startnumber += 1;

                        db.AddServiceCarScheduleDetail(scheduledetail);
                    }

                    db.SubmitChanges();
                }
                else
                {
                    // Date already planned with timeslots
                    throw new ArgumentException("Kapacitet allerede oprettet for denne dag. Venligst vælg dag og tilføj manuelt.");
                }

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }
    }
}